package com.winning.joiner.magiccube.tool.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.joda.time.DateTime;

import com.winning.joiner.magiccube.common.constant.Constants;
import com.winning.joiner.magiccube.common.utils.FieldNameUtils;
import com.winning.joiner.magiccube.tool.config.GenConfig;
import com.winning.joiner.magiccube.tool.config.MappingConfig;
import com.winning.joiner.magiccube.tool.constant.ColumnFieldMap;
import com.winning.joiner.magiccube.tool.domain.ColumnInfo;
import com.winning.joiner.magiccube.tool.domain.TableInfo;

/**
 * 代码生成器 工具类
 * 
 * @author shang.li
 */
public class GenUtils
{
    /** 项目空间路径 */
    private static  String projectPath = "main/java";

    /** mybatis空间路径 */
    private static  String myBatisPath = "main/resources/mybatis";

    /** html空间路径 */
    private static  String templatesPath = "main/resources/templates";

    /**
     * 设置列信息
     */
    public static List<ColumnInfo> transColums(List<ColumnInfo> columns)
    {
        // 列信息
        List<ColumnInfo> columsList = new ArrayList<>();
        for (ColumnInfo column : columns)
        {
            // 列名转换成Java属性名
            String attrName = FieldNameUtils.convertToCamelCase(column.getColumnName());
            column.setAttrName(attrName);
            column.setAttrname(FieldNameUtils.uncapitalize(attrName));

            // 列的数据类型，转换成Java类型
            String attrType = ColumnFieldMap.javaTypeMap.get(column.getDataType());
            if(column.getDataType().equals("NUMBER")){
            	if(column.getDataScale()!=null&& column.getDataScale()>0){
            		attrType="BigDecimal";
            	}
            }
            column.setAttrType(attrType);
            String jdbcType=ColumnFieldMap.javaToJdbcTypeMap.get(column.getAttrType());
            column.setJdbcType(jdbcType);
            columsList.add(column);
        }
        return columsList;
    }
    /**
     * 获取主键信息
     * @param columns
     * @return
     */
    public static List<ColumnInfo> getPrimaryKeyColumns(List<ColumnInfo> columns)
    {
        // 列信息
        List<ColumnInfo> primaryKeyColumns = new ArrayList<>();
        for (ColumnInfo column : columns){
        	if(column.getPkFlag()){
        		primaryKeyColumns.add(column);
        	}
        }
        if(primaryKeyColumns.isEmpty()){
            primaryKeyColumns.add(columns.get(0));
        }
        return primaryKeyColumns;
    }

    /**
     * 获取模板信息
     * 
     * @return 模板列表
     */
    public static VelocityContext getVelocityContext(TableInfo table,GenConfig genConfig)
    {
        // java对象数据传递到模板文件vm
        VelocityContext velocityContext = new VelocityContext();
        String packageName = genConfig.getPackageName();
        velocityContext.put("tableName", table.getTableName());
        velocityContext.put("tableComment", replaceKeyword(table.getTableComment()));
        velocityContext.put("primaryKeys", table.getPrimaryKeys());
        velocityContext.put("className", table.getClassName());
        velocityContext.put("classname", table.getClassname());
        velocityContext.put("moduleName", GenUtils.getModuleName(packageName));
        velocityContext.put("columns", table.getColumns());
        velocityContext.put("package", packageName);
        velocityContext.put("author", genConfig.getAuthor());
        velocityContext.put("datetime",new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        return velocityContext;
    }

    /**
     * 获取模板信息
     * 
     * @return 模板列表
     */
    public static List<String> getTemplates()
    {
        List<String> templates = new ArrayList<String>();
        templates.add("templates/vm/java/domain.java.vm");
        templates.add("templates/vm/java/Mapper.java.vm");
        templates.add("templates/vm/java/Service.java.vm");
        templates.add("templates/vm/java/ServiceImpl.java.vm");
        templates.add("templates/vm/java/Controller.java.vm");
        templates.add("templates/vm/xml/Mapper.xml.vm");
        templates.add("templates/vm/java/BO.java.vm");
        templates.add("templates/vm/java/BOImpl.java.vm");
        templates.add("templates/vm/java/DTO.java.vm");
        templates.add("templates/vm/java/desgin.txt.vm");
        return templates;
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName,GenConfig genConfig)
    {
    	//首先判断是否在映射表里面有没有表和实体关系
    	if(StringUtils.isNotBlank(MappingConfig.classNameMap.get(tableName))){
    		return MappingConfig.classNameMap.get(tableName);
    	}
        if (Constants.AUTO_REOMVE_PRE.equals(genConfig.getAutoRemovePre()))
        {
            tableName = tableName.substring(tableName.indexOf("_") + 1);
        }
        if (StringUtils.isNotEmpty(genConfig.getTablePrefix()))
        {
            tableName = tableName.replace(genConfig.getTablePrefix(), "");
        }
        return FieldNameUtils.convertToCamelCase(tableName);
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, TableInfo table, String moduleName,String packagePath)
    {
        // 小写类名
        String classname = table.getClassname();
        // 大写类名
        String className = table.getClassName();
        String javaPath = projectPath + "/" + packagePath + "/";
        String mybatisPath = myBatisPath + "/" + moduleName + "/" + className;
        String htmlPath = templatesPath + "/" + moduleName + "/" + classname;

        if (template.contains("domain.java.vm"))
        {
            return javaPath + "entity" + "/" + className + "DO.java";
        }

        if (template.contains("Mapper.java.vm"))
        {
            return javaPath + "dao" + "/" + className + "DAO.java";
        }

        if (template.contains("Service.java.vm"))
        {
            return javaPath + "service" + "/" + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm"))
        {
            return javaPath + "service" + "/impl/" + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm"))
        {
            return javaPath + "controller" + "/" + className + "Controller.java";
        }

        if (template.contains("BO.java.vm"))
        {
            return javaPath + "bo" + "/" + className + "BO.java";
        }

        if (template.contains("BOImpl.java.vm"))
        {
            return javaPath + "bo"+"/impl/" + className + "BOImpl.java";
        }

        if (template.contains("DTO.java.vm"))
        {
            return javaPath + "dto"+"/"+ className + "DTO.java";
        }

        if (template.contains("Mapper.xml.vm"))
        {
            return mybatisPath + "Mapper.xml";
        }


        if (template.contains("desgin.txt.vm"))
        {
            return mybatisPath + "desgin.txt";
        }
        return null;
    }

    /**
     * 获取模块名
     * 
     * @param packageName 包名
     * @return 模块名
     */
    public static String getModuleName(String packageName)
    {
        int lastIndex = packageName.lastIndexOf(".");
        int nameLength = packageName.length();
        String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength);
        return moduleName;
    }

    public static String replaceKeyword(String keyword)
    {
    	if(keyword==null)
    		return null;
        String keyName = keyword.replaceAll("(?:表|信息)", "");
        return keyName;
    }
    
    
    public static void main(String[] args) {
    	String string = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    	
    	
    	System.out.println(string);
	}
}
